package com.neusoft.yiyang.bed.service.impl;

import com.neusoft.yiyang.common.entity.bed.Bed;
import com.neusoft.yiyang.common.entity.bed.BedUsage;
import com.neusoft.yiyang.common.enums.BedStatus;
import com.neusoft.yiyang.bed.mapper.BedMapper;
import com.neusoft.yiyang.bed.mapper.BedUsageMapper;
import com.neusoft.yiyang.bed.service.BedAllocationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class BedAllocationServiceImpl implements BedAllocationService {

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private BedUsageMapper bedUsageMapper;

    @Override
    public void assignBedToCustomer(Integer customerId, Integer bedId, Date endDate) {
        // 1. 获取床位并更新床位状态为 "occupied"
        Bed bed = bedMapper.selectById(bedId);
        if (bed != null && bed.getStatus() == BedStatus.free) {  // 检查床位是否空闲
            bed.setStatus(BedStatus.occupied);  // 更新床位状态为 "已占用"
            bedMapper.updateById(bed);
        }

        // 2. 创建床位使用记录，设置开始日期和结束日期
        BedUsage bedUsage = new BedUsage();
        bedUsage.setCustomerId(customerId);
        bedUsage.setBedId(bedId);
        bedUsage.setStartDate(new Date());  // 当前时间作为开始日期
        bedUsage.setEndDate(endDate != null ? endDate : new Date(9999, 12, 31));  // 使用前端传回的退住时间，默认最大日期

        bedUsageMapper.insert(bedUsage);
    }

    @Override
    public void swapBedForCustomer(Integer customerId, Integer oldBedId, Integer newBedId, Date endDate) {
        // 1. 更新原床位的结束日期
        BedUsage oldBedUsage = bedUsageMapper.selectByCustomerIdAndBedId(customerId, oldBedId);
        if (oldBedUsage != null) {
            oldBedUsage.setEndDate(new Date());  // 当前时间作为结束日期
            bedUsageMapper.updateById(oldBedUsage);
        }

        // 2. 更新原床位的状态为 "free"
        Bed oldBed = bedMapper.selectById(oldBedId);
        if (oldBed != null) {
            oldBed.setStatus(BedStatus.free);  // 更新为 "空闲"
            bedMapper.updateById(oldBed);
        }

        // 3. 分配新床位，并更新床位状态为 "occupied"
        Bed newBed = bedMapper.selectById(newBedId);
        if (newBed != null && newBed.getStatus() == BedStatus.free) {  // 检查新床位是否空闲
            newBed.setStatus(BedStatus.occupied);  // 更新床位状态为 "已占用"
            bedMapper.updateById(newBed);

            // 4. 在 bed_usage 表中插入新的床位使用记录
            BedUsage newBedUsage = new BedUsage();
            newBedUsage.setCustomerId(customerId);
            newBedUsage.setBedId(newBedId);
            newBedUsage.setStartDate(new Date());  // 当前时间作为开始日期
            newBedUsage.setEndDate(endDate != null ? endDate : new Date(9999, 12, 31));  // 使用前端传回的退住时间，默认最大日期
            bedUsageMapper.insert(newBedUsage);
        }
    }

    // 获取指定楼栋和楼层的所有不同房间号
    public List<String> getDistinctRoomsByFloor(Integer buildingNo, Integer floor) {
        return bedMapper.getDistinctRoomsByFloor(buildingNo, floor);
    }


}
